# -*- coding: utf-8 -*-

'''

@author: wyndem
@Emil:   wyndem.wen@timevary.com
@FileName: tool.py
@Time: 2018/7/19 14:20
@Description: 工具类

'''
import logging
import random
import time
from queue import Queue

# 浏览器UA
from urllib.parse import urlparse

import requests

from novel.utils.user_agents import agents

uas =agents

q = Queue()
logging.basicConfig(level=logging.DEBUG,
                format='%(levelname)s： %(asctime)s ---%(filename)s(%(name)s)---->  %(message)s',
                datefmt='%a, %d %b %Y %H:%M:%S',
                )


def retry(fun):
    """
    重试装饰器
    :param fun:
    :return:
    """
    def force(*args, **kwargs):
        degree = 0
        while  degree<=10:
            try:
                f=fun(*args, **kwargs)
                return f
            except Exception as e :
                degree+=1

    return force

def itemtype(type):
    def wrapper(func):
        def inner_wrapper(*args, **kwargs):
            if isinstance(args[1],type):
                return func(*args, **kwargs)
            else:
                return args[1]
        return inner_wrapper
    return wrapper

@retry
def init_ips():
    if is_PRo:
        ips = requests.get(PROIP).json()
        if ips.get('code') == 5:
            ip=ips.get("msg").split('登录IP')[0]
            requests.get('http://http.zhiliandaili.com/Users-whiteIpAddNew.html?appid=1606&appkey=e48efc6dd23b9c5a0ee524ceac7331aa&whiteip='+ip+'&index=3')
        if ips.get('code')==0:
            ips=ips.get("data")
            for ip in ips:
                q.put(ip.get('IP'))

def lodingIP():
    ips = requests.get(
        "http://api.ip.data5u.com/socks/get.html?order=d6965a3d27bdbab78696aa1bcde82491&json=1&type=1&sep=3h").json()

    if ips.get("success") == True:
        data = ips.get("data")[0]
        ip = data.get("ip")
        post = data.get("port")
        ttl=int(int(data.get('ttl'))*0.001)
        wuyouXy = str(ip) + ":" + str(post)
        TOOL.r_set(ip,wuyouXy,TOOL.r2,ttl)



class Tool():

    def __init__(self):
        self.proxys=''
        self.proxy_num=3


    '获取代理IP'
    def getProXY(self):
        ip=self.getMgXY()
        return ip

    def logging(self):
        return logging

    '获取代理IP'
    def getJLProXY(self):
        if  not q.empty():
            if self.proxys=='' or self.proxy_num==0:
                self.proxys=q.get()
                self.proxy_num=1
            self.proxy_num-=1
            return self.proxys
        elif is_PRo:
            init_ips()
            return self.getProXY()
        else:
            return ''



    '蘑菇代理'
    def getMgXY(self):
        return  'transfer.mogumiao.com:9001'

    '生成密码'
    def create_uid(self):

        # capitalization = [chr(i) for i in range(65, 91)]  # 大写字母
        # lowercase = [chr(i) for i in range(97, 123)]  # 小写字母
        number = [chr(i) for i in range(48, 58)]  # 数字

        # cap = random.sample(capitalization, random.randint(1, 3))
        # low = random.sample(lowercase, random.randint(5, 8))
        num = random.sample(number, random.randint(4, 6))

        str = ''
        value = str.join(num)   # 将取出的十个随机数进行重新合并

        for v in value:
            n = random.randint(1, len(value))
            str += value[n - 1:n]

        return str


    '获取伪装浏览器头'
    def getHeaders(self):
        appKey = "cTA5SmxBTHZWd1FpTXFtdDpCSHpJUEI0Mno3ZmlXT3lQ"
        headers=HEADERS
        if headers==None or headers=='' or len(headers)==0:
            headers={"Accept-Encoding":"gzip, deflate, br",
                     "Accept-Language":"zh-CN,zh;q=0.8",
                     "Cache-Control":"max-age=0",
                     "Connection":"keep-alive",
                     "Proxy-Authorization": 'Basic '+ appKey}
        if headers.get('User-Agent')==None:
            headers['User-Agent'] = uas[random.randint(0, len(uas)-1)]
        return headers


    def getUA(self) -> str:
        """
        获取ua
        :return:
        """
        return uas[random.randint(0, len(uas)-1)]

    def get_host_url(self, url):
        r = urlparse(url)
        return  r.netloc




is_PRo=True
num=200
#代理地址
PROIP='http://ip.11jsq.com/index.php/api/entry?method=proxyServer.generate_api_url&packid=0&fa=0&fetch_key=&qty='+str(num)+'&time=100&pro=&city=&port=1&format=json&ss=5&css=&ipport=1&dt=1&specialTxt=3&specialJson='
#浏览器Headers
HEADERS={}


TOOL=Tool()
